package com.eduhzy.ttw.clazz.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.EditText;
import android.widget.Switch;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.clazz.R;
import com.eduhzy.ttw.clazz.R2;
import com.eduhzy.ttw.clazz.di.component.DaggerAddReviewComponent;
import com.eduhzy.ttw.clazz.di.module.AddReviewModule;
import com.eduhzy.ttw.clazz.mvp.contract.AddReviewContract;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzAddScore;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzReviewIcon;
import com.eduhzy.ttw.clazz.mvp.model.entity.HomeData;
import com.eduhzy.ttw.clazz.mvp.presenter.AddReviewPresenter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-5 12:20:37
 */
@Route(path = RouterHub.CLAZZ_ADDREVIEWACTIVITY)
public class AddReviewActivity extends BaseActivity<AddReviewPresenter> implements AddReviewContract.View {
    @Autowired(name = Constants.PARCELABLE_DATA)
    HomeData mBean;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.iv_icon)
    QMUIRadiusImageView mIvIcon;
    @BindView(R2.id.et_title)
    EditText mEtTitle;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.switcher)
    Switch mSwitcher;
    @BindView(R2.id.btn_submit)
    QMUIRoundButton mBtnSubmit;

    @Inject
    BaseQuickAdapter<ClazzAddScore, AutoBaseViewHolder> mAdapter;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    GridSpacingItemDecoration mDecoration;
    private String mScore = "3";
    private ClazzReviewIcon mIcon;
    private List<ClazzReviewIcon> mData;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerAddReviewComponent
                .builder()
                .appComponent(appComponent)
                .addReviewModule(new AddReviewModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.clazz_activity_add_review;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        getData();
        mRvList.setLayoutManager(mLayoutManager);
        mRvList.setAdapter(mAdapter);
        mRvList.addItemDecoration(mDecoration);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            ClazzAddScore score = mAdapter.getData().get(position);
            if (score.isSelect()) {
                return;
            } else {
                score.setSelect(true);
                this.mScore = score.getScore();
            }
            for (int i = 0; i < mAdapter.getData().size(); i++) {
                if (i == position) continue;
                mAdapter.getData().get(i).setSelect(false);
            }
            mAdapter.notifyDataSetChanged();

        });
        initScore();
    }

    private void initScore() {
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
            for (int i = 0; i < 10; i++) {
                emitter.onNext(String.valueOf(i + 1));
            }
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle((IView) getActivity()))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        ClazzAddScore data = new ClazzAddScore();
                        if (s.equals("3")) {
                            data.setSelect(true);
                        }
                        data.setScore(s);
                        mAdapter.getData().add(data);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void getData() {
        mPresenter.getIconList(mBean.getType());
    }

    @Override
    public void showLoading() {
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {
        mEmptyView.hide();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void update(List<ClazzReviewIcon> data) {
        if (ObjectUtils.isNotEmpty(data)) {
            this.mData = data;
            this.mIcon = data.get(0);
            Glide.with(this)
                    .load(data.get(0).getUrl(getActivity()))
                    .into(mIvIcon);
        }
    }

    @Subscriber(tag = RouterHub.CLAZZ_ADDREVIEWACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.CHOOSE_REVIEW_ICON:
                mIcon = (ClazzReviewIcon) msg.obj;
                if (ObjectUtils.isNotEmpty(mIcon)) {
                    Glide.with(this)
                            .load(mIcon.getUrl(getActivity()))
                            .into(mIvIcon);
                }
                break;
            default:
        }
    }

    @OnClick(R2.id.btn_submit)
    public void onViewClicked() {
        if (RxUtil.showEditTip(this, mEtTitle, "请输入评语名称")) {
            return;
        }
        String title = mEtTitle.getText().toString();
        if (title.length() > 6) {
            showMessage("评语不能超过6个汉字");
            return;
        }
        MobclickAgent.onEvent(getActivity(),"ttw_review_add");
        mPresenter.evaluateTagSave(mBean.getClassId(), mIcon.getId(), title, mScore, mBean.getType(), mSwitcher.isChecked() ? 1 : 0);

    }

    @OnClick(R2.id.iv_icon)
    public void onIconViewClicked() {
        ARouter.getInstance().build(RouterHub.CLAZZ_CHOOSEICONACTIVITY)
                .withString(Intent.EXTRA_TITLE, "选择图标")
                .withParcelableArrayList(Constants.PARCELABLE_LIST, (ArrayList<? extends Parcelable>) mData)
                .navigation(getActivity());
    }
}
